package tuvalLib;
import ikaz.PresetWarnings;
import arayuz.CepMuvakkitG;
import astroLib.APC_Time;
import astroLib.Settings;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import lang.LocalizationSupport;
import javax.microedition.lcdui.*;
import astroLib.HijriCalendar;

public class SCanvas extends Canvas implements CommandListener {
    private int width,  height;
    private Image imHoly = null;
    private Font fontSP, fontMP,fontSPB;
    private int fontHeight, fontSize=8;
    private String fajrStr,  sunRiseStr,  zuhrStr,  asrStr,  magribStr,  ishaStr;
    private double MJD0h,timeZone,MJD;
    private double[] fiveTimes= new double[6];
    private String timeStr, gregorianCalendar,  locationName;
    public  static int closestOne;
    private double timeLeft;
      //private byte dayofMonth;
    private Command hideCommand,menuCommand;
    public static boolean isCurrentDay=true;
    //public static boolean isDayChanged=false;
    public static boolean isWarningOn=false,afterMagrib=false;
    private boolean isMilitary=true;
    private Calendar now;//, modifiedJulianDay;
    public CepMuvakkitG midlet;
    private  String[] timesStrings=new String[6];
    private  String[] timesNames=new String[6];
    private Timer iTimer,dayTurnTimer;
    private TimerTask iTask,dayTurnTask;
   static private long HOUR_IN_MILLISEC =3600000;
    private HijriCalendar hijriCalendar;
   
    public SCanvas() {
         fontSP = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, fontSize);
         fontSPB = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, fontSize);
         fontMP = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, fontSize);
         fontHeight = fontSP.getHeight();
         timesNames=new String[]{lang.LocalizationSupport.getMessage("IMSAK"), LocalizationSupport.getMessage("GUNES"), LocalizationSupport.getMessage("OGLE"), LocalizationSupport.getMessage("IKINDI"), LocalizationSupport.getMessage("AKSAM"),LocalizationSupport.getMessage("YATSI")};
         width = getWidth();
         height = getHeight();
     
        try {
	    // Set up this canvas to listen to command events
	    setCommandListener(this);
	    // Add the Exit commandastro
	     menuCommand = new Command(LocalizationSupport.getMessage("MENU"), Command.ITEM, 0);
         hideCommand = new Command(LocalizationSupport.getMessage("HIDE"), Command.BACK, 0);
         addCommand(menuCommand );
         addCommand(hideCommand);
        } catch(Exception e) { e.printStackTrace();}
        iTimer = new Timer();
        iTask =  new TimerTask(){ public void run(){repaint();}}; // makes a request for a delayed call to paint()...   	}
        iTimer.scheduleAtFixedRate(iTask, 1000 ,1000);

        dayTurnTimer=new Timer();
        dayTurnTask=new TimerTask()
        {public void run(){
             MJD0h = getMJD0h();
            // modifiedJulianDay=APC_Time.CalDat(MJD0h+timeZone/24.0);
             gregorianCalendar=APC_Time.DateTime(MJD0h+timeZone/24.0);
             Settings.getSalatTimes(MJD0h, fiveTimes);
             isCurrentDay=true;
             isWarningOn=false;
             setTimesStr(fiveTimes);
             repaint();
         }
        };
       long timLeftToDayTurn=(long)((24-getTimeInHour())* HOUR_IN_MILLISEC);
       //System.out.println("timLeftToDayTurn ="+timLeftToDayTurn);
       dayTurnTimer.scheduleAtFixedRate(dayTurnTask, timLeftToDayTurn,24*HOUR_IN_MILLISEC);
       //setFullScreenMode(Settings.optionPref.getIsFullScreen());

    }

    public void paint(Graphics g) {
        //        synchronized (g) {
        g.setColor(0, 0, 0);
        g.fillRect(0, 0, width, height);
        g.setColor(0, 0, 60);
        g.fillTriangle(0, 0, 2*fontHeight, 2*fontHeight, 2*fontHeight,0);
        g.fillRect(2*fontHeight,0, width-4*fontHeight, 2*fontHeight);
        g.fillTriangle(width,0,width-2*fontHeight, 2*fontHeight, width-2*fontHeight, 0);
        //g.setColor(255, 255, 255);
        g.setColor(255,0, 0);
        int yPos,line = 0;
        g.setFont(fontMP);
        setTimeText() ;
        g.drawString(locationName +"@"+gregorianCalendar , width / 2, line++ * fontHeight, Graphics.HCENTER | Graphics.TOP);
        String dayStr= "";
         if (isCurrentDay) 

        {   //g.drawString(timeStr, width / 4, line++ * fontHeight, Graphics.HCENTER | Graphics.TOP);
             ///line--;
            dayStr= getDay();
  //     g.setColor(255,255,255);
    //        g.setFont(fontSP);
           dayStr=timeStr+dayStr;

         }
         g.drawString(dayStr, width / 2, line++ * fontHeight, Graphics.HCENTER | Graphics.TOP);
      //  g.setColor(255,250, 0);
       //  g.setColor(255,120, 40);
     
     //     g.drawString(getDay(), 3*width /4 , line++* fontHeight, Graphics.HCENTER | Graphics.TOP);
       // g.drawString(getDay()+"", width , --line*fontHeight, Graphics.HCENTER | Graphics.TOP);
   
        for (int i = 0; i <= 5; i++) {
            yPos = (++line) * fontHeight;
            g.setFont(fontSP);
            if (i==(closestOne-1)) g.setFont(fontSPB);
            g.setColor(65, 105, 225);
            if (i == 0 || i == 2 || i == 4) g.setColor(135, 206, 250);
            g.drawString(timesNames[i], width / 4, yPos, Graphics.BASELINE | Graphics.LEFT);
            g.drawString(":", width / 2, yPos, Graphics.BASELINE | Graphics.HCENTER);
            g.setColor(4, 105, 225);
            if (i == 0 || i == 2 || i == 4) g.setColor(135, 206, 250);
            g.drawString(timesStrings[i], 2 * width / 3, yPos, Graphics.BASELINE | Graphics.HCENTER);
            //System.out.println(timesStrings[i]);

        }
        if (isCurrentDay)
        {int green=(int) (this.timeLeft * 40);
        if (green>255) green=255;
        g.setColor(255, green, 0);
        setTimeLeft();
        g.drawString(">>"+" "+APC_Time.SecTime(this.timeLeft)+" "+lang.LocalizationSupport.getMessage("MINLEFT")+" <<", width / 2, (line++)*fontHeight+8, Graphics.HCENTER | Graphics.TOP);}
         //g.setColor(65, 105, 225);
        g.setColor(0, 0,60);

   /*     g.fillTriangle(0,height,fontHeight, height-2*fontHeight, 2*fontHeight,height);
        g.fillRect(fontHeight, height-2*fontHeight, width-2*fontHeight, 2*fontHeight);
        g.fillTriangle(width,height,width-fontHeight, height-2*fontHeight, width-fontHeight, height);*/

        g.fillTriangle(0,height,2*fontHeight, height-2*fontHeight, 2*fontHeight,height);
        g.fillRect(2*fontHeight, height-2*fontHeight, width-4*fontHeight, 2*fontHeight);
        g.fillTriangle(width,height,width-2*fontHeight, height-2*fontHeight, width-2*fontHeight, height);
/*           g.fillTriangle(0,height,fontHeight, height-fontHeight, fontHeight,height);
        g.fillRect(fontHeight, height-fontHeight, width-2*fontHeight, fontHeight);
        g.fillTriangle(width,height,width-fontHeight, height-fontHeight, width-fontHeight, height);*/
       // g.setColor(205, 0,0);
        //g.setColor(254,124, 47);
         //g.setColor(0, 255, 0);
        g.setColor(0, 255, 0);
        MJD=(int)(MJD0h+timeZone/24.0);
        hijriCalendar=getHijriCalendar(MJD,afterMagrib);
        g.setFont(fontMP);

        g.drawString (hijriCalendar.getDay(), width / 2, height-fontHeight,  Graphics.BOTTOM| Graphics.HCENTER);
        g.drawString (hijriCalendar.getHicriTakvim(), width / 2, height,  Graphics.BOTTOM| Graphics.HCENTER);
        //g.drawString (hijriCalendar.getHijriDay()+"  "+hijriCalendar.getHijriMonthName()+" "+hijriCalendar.getDay(), width / 2, height,  Graphics.BOTTOM| Graphics.HCENTER);
       // g.drawString (hijriCalendar.getDay(), width / 2, height-fontHeight,  Graphics.BOTTOM| Graphics.HCENTER);
        //Vertical Text for Holy Days
        g.setFont(fontMP);
        String holyDayStr= hijriCalendar.checkIfHolyDay();
        if (holyDayStr.length()!=0)
        { int sw=fontMP.stringWidth( holyDayStr);
          imHoly = Image.createImage(sw+ fontHeight, fontHeight+fontHeight/4);
          Graphics graphics = imHoly.getGraphics();
          graphics.setFont(fontMP);
          graphics.setColor(217, 250, 181);
          graphics.fillRoundRect(0,0, imHoly.getWidth()-1, imHoly.getHeight()-1, 20, 20);
          graphics.setColor(20, 80, 52);
          graphics.drawString(holyDayStr,  (imHoly.getWidth() / 2) - (sw/ 2), 0,  Graphics.TOP | Graphics.LEFT);
          g.drawRegion(imHoly, 0, 0, imHoly.getWidth(),  imHoly.getHeight(), 6,0, getHeight() / 2, Graphics.VCENTER | Graphics.LEFT);
        }
          //      }
    }
  public void setPreferences(Settings preferences) {
       // this.preferences=preferences;
        this.MJD0h=getMJD0h();
        Settings.getSalatTimes(MJD0h, fiveTimes);
        setTimesStr(fiveTimes);
        this.locationName =Settings.locationPrefer.getLocation();
        this.isMilitary=Settings.optionPref.getIsMilitary();
        //modifiedJulianDay=APC_Time.CalDat();
        this.gregorianCalendar=APC_Time.DateTime(MJD0h+timeZone/24.0);
        //setGregorianCalendar(modifiedJulianDay);
      //  this.gregorianCalendar=
       // System.out.println("Settings.optionPref.getIsFullScreen()"+Settings.optionPref.getIsFullScreen());
        setFullScreenMode(Settings.optionPref.getIsFullScreen());
        setFontSize(Settings.optionPref.getFontSize());
        this.repaint();

    }

    private double getTimeInHour() {
        return getHour()+getMin()/60.0+getSec()/3600.0;
    }

   private void setTimesStr(double[] fiveTimes) {

      this.fajrStr = APC_Time.Time(fiveTimes[0],isMilitary);
      this.sunRiseStr = APC_Time.Time(fiveTimes[1],isMilitary);
      this.zuhrStr = APC_Time.Time(fiveTimes[2],isMilitary);
      this.asrStr = APC_Time.Time(fiveTimes[3],isMilitary);
      this.magribStr = APC_Time.Time(fiveTimes[4],isMilitary);
      this.ishaStr = APC_Time.Time(fiveTimes[5],isMilitary);
      this.timesStrings= new String[]{fajrStr, sunRiseStr, zuhrStr, asrStr, magribStr, ishaStr};
/*      System.out.print(gregorianCalendar+" ");
      for (int i = 0; i <= 5; i++) {
     System.out.print(timesStrings[i]+" ");
      }
 *
      System.out.println();*/
     if (isWarningOn==false)
     {
        setTimeLeft();
        new PresetWarnings(Settings.warningPref,fiveTimes,getTimeInHour(),midlet);
       // isWarningOn=true;
     }
      // if (isCurrentDay){
     //     setWarningAlarm=new OpenWarnings(fiveTimes, getTimeInHour(), preferences,Display.getDisplay(this.midlet));}
      
   }

  private void setTimeText ()
    {
     this.timeStr=intTwoDigit(getHour())+":"+intTwoDigit(getMin())+":"+intTwoDigit(getSec())+" ";

    }

  public final static int getHour() {
   	   return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
     }

  public final static int getMin() {
    	return Calendar.getInstance().get(Calendar.MINUTE);
    }

  public final static int getSec() {
    	return Calendar.getInstance().get(Calendar.SECOND);
    }
  

  public final static String intTwoDigit(int i) {
         return ((i < 10) ? "0" : "") + i;
  }
   public final static String getDay() {
        String daysName[]={ LocalizationSupport.getMessage("SUNDAY"),
        LocalizationSupport.getMessage("MONDAY"),LocalizationSupport.getMessage("TUESDAY"),LocalizationSupport.getMessage("WEDNESDAY"),LocalizationSupport.getMessage("THURSDAY"),
        LocalizationSupport.getMessage("FRIDAY"),LocalizationSupport.getMessage("SATURDAY")};
    	return daysName[  Calendar.getInstance().get(Calendar.DAY_OF_WEEK)-1];

    }

  private double getMJD0h()
  {
      now = Calendar.getInstance();
       if (Settings.locationPrefer.getTimeZoneSrc()!=0)
         {
            timeZone=Settings.locationPrefer.getTimeZone();
            if (Settings.locationPrefer.getIsDSTOn()) timeZone++;
        }
        else
            timeZone=now.getTimeZone().getRawOffset()/(60*60*1000);

        return APC_Time.Mjd(now.get(Calendar.YEAR), now.get(Calendar.MONTH)+1,now.get(Calendar.DAY_OF_MONTH),0,0,0)-timeZone/24.0;
  }


/*   private void setGregorianCalendar (double Mjd)
            {
               dayofMonth=(byte)now.get(Calendar.DAY_OF_MONTH);
                gregorianCalendar=dayofMonth
                +"/"+(now.get(Calendar.MONTH))
                +"/"+now.get(Calendar.YEAR);
            }
*/

   private void setFontSize(byte fontSize) {
        switch (fontSize) {
            case 0:
                this.fontSize = 8;
                break;
            case 1:
                this.fontSize = 0;
                break;
            case 2:
                this.fontSize = 16;
                break;
        }
         fontSP = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, this.fontSize);
         fontSPB = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, this.fontSize);
         fontMP = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, this.fontSize);
         fontHeight = fontSP.getHeight();
    }
private  void setTimeLeft() {
        now=Calendar.getInstance();
        this.timeLeft=getTimeLeft(now);
       /* if  (timeLeft<0.0125)
            isWarningTime=true;
            System.out.print("45 saniyeden az kald?");*/
      }
  private HijriCalendar getHijriCalendar(double MJD,boolean afterMagrib) {

        //(int)Settings.optionPref.getHijriCorrection();
        hijriCalendar = new HijriCalendar(MJD+Settings.optionPref.getHijriCorrection(),afterMagrib);
        return hijriCalendar;

    }
public double getTimeLeft  (Calendar now )
    {
       timeLeft=0;
       closestOne=0;

       double timeInHour=now.get(Calendar.HOUR_OF_DAY)+now.get(Calendar.MINUTE)/60.0+now.get(Calendar.SECOND)/3600.0;
       afterMagrib=(timeInHour>fiveTimes[4]);
       while ((timeLeft<=0)&&(closestOne<=5)){
           timeLeft=fiveTimes[closestOne]-timeInHour;
           closestOne++;
       }
       if (timeLeft<0&&(closestOne==6))
       {   closestOne=1;
           timeLeft=timeLeft+24-fiveTimes[5]+fiveTimes[0];
       }
       return timeLeft;
    }
    protected  void keyPressed(int keyCode) {


        int pressAction = getGameAction(keyCode);
               if (pressAction==RIGHT||pressAction==UP||keyCode==54) {

                MJD0h++;
                //modifiedJulianDay=APC_Time.CalDat(MJD0h+timeZone/24.0);
                 this.gregorianCalendar=APC_Time.DateTime(MJD0h+timeZone/24.0);
                //this.gregorianCalendar=
              //  setGregorianCalendar( modifiedJulianDay);
                Settings.getSalatTimes(MJD0h, fiveTimes);
                setTimesStr(fiveTimes);
                SCanvas.isCurrentDay=false;
                // setWarningAlarm.timer.cancel();
                // setWarningAlarm=null;

               }
               else if (pressAction ==FIRE){
                   this.MJD0h = getMJD0h();
                   //modifiedJulianDay=APC_Time.CalDat(MJD0h+timeZone/24.0);
                    this.gregorianCalendar=APC_Time.DateTime(MJD0h+timeZone/24.0);
                   Settings.getSalatTimes(MJD0h, fiveTimes);
                   setTimesStr(fiveTimes);
                    SCanvas.isCurrentDay=true;
                   //setWarningAlarm=new OpenWarnings(fiveTimes, getTimeInHour(), preferences,Display.getDisplay(this.midlet));
               }
               else if(pressAction == LEFT||pressAction == DOWN) {
                MJD0h--;
                this.gregorianCalendar=APC_Time.DateTime(MJD0h+timeZone/24.0);
                //modifiedJulianDay=APC_Time.CalDat(MJD0h+timeZone/24.0);
                //setGregorianCalendar( modifiedJulianDay);
                Settings.getSalatTimes(MJD0h, fiveTimes);
                setTimesStr(fiveTimes);
                SCanvas.isCurrentDay=false;
                //setWarningAlarm.timer.cancel();
                //setWarningAlarm=null;
               
                }
		// make sure to repaint
                afterMagrib=false;
		this.repaint();
    }
    public void commandAction(Command arg0, Displayable arg1) {

          if(arg0==menuCommand)
         {
            Display.getDisplay(midlet).setCurrent(midlet.getSecenekler());
         }  else if (arg0==hideCommand)
           {
             Display.getDisplay(midlet).setCurrent(null);
           } 

            repaint();
    }
}
